package com.smh.demo1.a04;

import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;

/**
 * @author shiminghui
 * @date 2025/4/10 20:31
 * @description: TODO
 */
public class A04Application {
    public static void main(String[] args) throws IOException {
        GenericApplicationContext context = new GenericApplicationContext();

        context.registerBean(Bean1.class);
        context.registerBean(Bean2.class);
        context.registerBean(Bean3.class);
        context.registerBean(Bean4.class);

        // 帮助实现值的注入
        context.getDefaultListableBeanFactory().setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());

        context.registerBean(AutowiredAnnotationBeanPostProcessor.class); // 注册一个注解处理器 处理autowire,valued注解

        context.registerBean(CommonAnnotationBeanPostProcessor.class); // 注册一个注解处理器 处理resource,postConstruct,preDestroy注解


        // 需要注册一个beanFactory的后处理器去解析ConfigurationProperties注解
        ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());

        // 主动加载环境变量
        StandardEnvironment environment = new StandardEnvironment();
        environment.getPropertySources().addLast(new ResourcePropertySource(new ClassPathResource("application.properties")));
        context.setEnvironment(environment);

        context.refresh(); // 刷新容器,执行beanFactory的后处理器,添加bean的后处理器,初始化bean

        // 测试获取配置文件里面的值

        String property = context.getEnvironment().getProperty("test.value");
        System.out.println(property);

        // 这里属性没有填充是因为环境变量里面没有配置test.value,而配置文件没有加载,因为不是spring掌管
        Bean4 bean = context.getBean(Bean4.class);
        System.out.println(bean);

        context.close();
    }


}
